<template>
  <div>
    <!-- :action="uploadAction" -->
    <!-- :headers="headers" -->
    <a-upload
      :class="{'disabled-upload':number !== 0 && fileList.length >= number}"
      name="file"
      :multiple="multiple"
      listType="picture-card"
      :fileList="fileList"
      :beforeUpload="beforeUpload"
      :disabled="disabled"
      :customRequest="customRequest"
      @change="handleChange"
      @preview="handlePreview"
    >
      <div  class="iconp">
        <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
        <div class="ant-upload-text">{{ text }}</div>
      </div>
      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel()">
        <img alt="example" style="width: 100%" :src="previewImage"/>
      </a-modal>
    </a-upload>
  </div>
</template>

<script>
// import { mapGetters } from 'vuex'
// import { ACCESS_TOKEN } from '@/store/mutation-types'
import { Upload as AUpload } from 'ant-design-vue'
import { postAction } from '@/services/manage'
import { getImgByFileNo, removeFile } from '@/services/common'
const uidGenerator = () => {
  return '-' + parseInt(Math.random() * 10000 + 1, 10)
}

export default {
  name: 'ZImageUpload',
  components: { AUpload },
  data() {
    return {
      uploadAction: process.env.VUE_APP_API_BASE_URL + '/file/upload',
      uploadLoading: false,
      headers: {},
      fileList: [],
      previewImage: '',
      previewVisible: false
    }
  },
  props: {
    text: {
      type: String,
      required: false,
      default: '上传'
    },
    value: {
      type: [String, Array],
      required: false
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false
    },
    multiple: {
      type: Boolean,
      required: false,
      default: false
    },
    // 新增number属性，用于判断上传数量
    number: {
      type: Number,
      required: false,
      default: 0
    },
    fileStorageType: { // 文件存储类型FileSystem、Database
      type: String,
      default: () => 'FileSystem'
    }
  },
  watch: {
    value: {
      handler(val, oldValue) {
        if (val instanceof Array) {
          this.initFileList(val)
        } else {
          this.initFileList(val ? val.split(',') : [])
        }
      },
      immediate: true
    }
    // token: {
    //   immediate: true,
    //   handler() {
    //     this.headers[ACCESS_TOKEN] = this.token
    //   }
    // }
  },
  // computed: {
  //   ...mapGetters(['token'])
  // },
  methods: {
    customRequest(options) {
      const { onSuccess, file, onProgress, onError } = options
      const params = new FormData()
      params.append('file', file)
      params.append('fileStorageType', this.fileStorageType)
      postAction('/file/upload', params, {
        timeout: 60000,
        onUploadProgress: ({ total, loaded }) => {
          onProgress({ percent: Number(Math.round((loaded / total) * 100).toFixed(2)) }, file) // 显示上传进度
        }
      }).then(res => {
        onSuccess(res, file) // 成功返回值
      }).catch(onError)
    },
    async initFileList(paths) {
      if (!paths || paths.length === 0) {
        this.fileList = []
        return
      }
      const oldPath = []
      this.fileList.forEach(item => {
        oldPath.push(item.url)
      })
      const fileList = []
      const axiosList = []
      paths.forEach((fileNo, i) => {
        if (oldPath.includes(fileNo) && this.fileList[i].thumbUrl) {
          fileList.push(this.fileList[i])// 已存在图片不重复请求
        } else {
          axiosList.push(getImgByFileNo(fileNo))
        }
      })
      Promise.all(axiosList).then((rspList) => {
        rspList.forEach((url, i) => {
          fileList.push({
            uid: uidGenerator(),
            name: paths[i],
            status: 'done',
            url: paths[i],
            thumbUrl: url, // base64图片
            fileNo: paths[i],
            response: {
              status: 'history',
              result: {
                fileName: paths[i],
                fileNo: paths[i]
              }
            }
          })
        })
      })
      this.fileList = fileList
    },
    beforeUpload: function(file) {
      var fileType = file.type
      if (fileType.indexOf('image') < 0) {
        this.$message.warning('请选择图片')
        return false
      }
    },
    handleChange(info) {
      let fileList = info.fileList
      if (this.number > 0) {
        fileList = fileList.slice(-this.number)
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          fileList = fileList.map((file) => {
            if (file.response) {
              file.name = file.response.result.fileName
              file.url = file.response.result.fileNo
              file.fileNo = file.response.result.fileNo
            }
            return file
          })
        } else {
          this.$message.error(`${info.file.name} 上传失败.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`)
      } else if (info.file.status === 'removed') {
        this.handleDelete(info.file)
      }
      // if (info.file.status !== 'removed' && info.file.type.indexOf('image') >= 0) { // 防止上传非图片时，组件显示错误
      // this.fileList = fileList
      // }
      this.fileList = fileList.filter(item => {
        return item.type.indexOf('image') >= 0
      })
      if (info.file.status === 'done' || info.file.status === 'removed') {
        this.handlePathChange()
      }
    },
    // 预览
    handlePreview(file) {
      this.previewImage = file.thumbUrl || file.url
      this.previewVisible = true
    },
    handlePathChange() {
      const uploadFiles = this.fileList
      let path = []
      if (!uploadFiles || uploadFiles.length === 0) {
        path = []
      }
      const arr = []
      for (let a = 0; a < uploadFiles.length; a++) {
        if (uploadFiles[a].status === 'done') {
          arr.push(uploadFiles[a].fileNo)
        } else {
          return
        }
      }
      path = this.value instanceof Array ? arr : arr.join(',')
      this.$emit('change', path)
    },
    handleDelete(file) { // 删除逻辑
      removeFile(file.url).then(res => {
        console.log(res)
      })
    },
    handleCancel() {
      this.previewVisible = false
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  }
}
</script>

<style lang="less">
.disabled-upload {
  .ant-upload-select-picture-card{
    display: none
  }
}
</style>
